import { Env } from '@/vite_env';
import axios, { AxiosError } from 'axios';
import {
  generateRequestKey,
  cancleSameReq,
  pendingRequests,
  setToken,
} from '@/libs/service/request';
import { cancleSameRes } from '@/libs/service/respones';
const env = import.meta.env as Env & ImportMetaEnv;

const http = axios.create({
  baseURL: env.VITE_BASE_URL,
  headers: { 'Content-Type': 'application/json' },
});

http.interceptors.request.use((req) => {
  setToken(req);
  cancleSameReq(req);
  return req;
});

http.interceptors.response.use(
  (res) => {
    cancleSameRes(res);
    return res;
  },
  (err: AxiosError) => {
    const key = err.config && generateRequestKey(err.config);
    if (key && pendingRequests.has(key)) {
      pendingRequests.delete(key);
    }
    return err.response;
  }
);

export default http;
